package huanzhao.erp.other.validator;

import huanzhao.erp.domain.annotation.CheckTask;
import huanzhao.erp.domain.po.Result;
import huanzhao.erp.domain.types.TaskType;
import huanzhao.erp.service.TaskService;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author April
 * 2024/7/24 下午6:34
 * @version 1.0
 */
@Component
public class TaskValidator implements ConstraintValidator<CheckTask, Long> {
    private final TaskService taskService;
    private boolean completable;
    private TaskType[] taskTypes;

    public TaskValidator(TaskService taskService) {
        this.taskService = taskService;
    }

    @Override
    public void initialize(CheckTask constraintAnnotation) {
        completable = constraintAnnotation.completable();
        taskTypes = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Long taskId, ConstraintValidatorContext constraintValidatorContext) {
        Result<?> result = taskService.checkTask(taskId, taskTypes, completable);
        if (result.isError()) {
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext
                    .buildConstraintViolationWithTemplate(result.getMessage())
                    .addConstraintViolation();
        }
        return !result.isError();
    }
}
